﻿#region Usings

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Web.Mvc;
using Rail.Net.Common;
using Rail.Net.Common.ActionFilters;
using Rail.Net.Common.Helpers;
using Rail.Net.Core.Model.Nonpersistent;
using WatiN.Core;

#endregion

namespace Rail.Net.Controllers
{
    [SetCulture]
    public class TgvController : Controller
    {
        public ActionResult Details(int id, bool forwardDirection)
        {
            var cookieName = forwardDirection ? Constants.FromProductOffersCookie : Constants.ToProductOffersCookie;
            var productOfferModel = Session[cookieName] as ProductOfferModel;
            if (productOfferModel != null)
            {
                var product = productOfferModel.Products.SingleOrDefault(p => p.Index == id);
                try
                {
                    var thread = new Thread(ThreadStart);
                    thread.SetApartmentState(ApartmentState.STA);
                    thread.Start(product);
                    thread.Join();
                }
                catch (Exception e)
                {
                    return Content(e.Message, "text/html", Encoding.UTF8);
                }
            }
            return Content("Session time out");
        }

        private static void ThreadStart(object param)
        {
            var product = param as Product2Model;
            if (product != null)
            {
                try
                {
                    using (var browser = new IE("http://www.tgv-europe.de/de/"))
                    {
                        browser.TextField(Find.ByName("ORIGIN_CITY")).TypeText("Wien");
                        browser.TextField(Find.ByName("DESTINATION_CITY")).TypeText("Paris");
                        browser.TextField(Find.ByName("OUTWARD_DATE")).TypeText("15/04/2011");
                        browser.Button(Find.ByName("action:searchTravel")).Click();
                        browser.WaitForComplete(3);

                        var div = browser.Div(Find.ById("resume-tab"));
                        if (div != null)
                        {
                            div.InnerHtml.Replace("src=\"", "src=\"http://www.tgv-europe.de/");
                            //product.TgvHtml = div.InnerHtml;
                        }
                        else
                        {
                            //product.TgvHtml = "No products were found!";
                        }
                    }
                }
                catch (Exception e)
                {
                    //product.TgvHtml = "No products were found!";
                }
            }
        }
    }
}